package com.youngball.shiro.service;


import com.youngball.business.exception.MyDefineException;
import com.youngball.business.utill.ConstantClass;
import com.youngball.business.utill.ObjectNullUtils;
import com.youngball.business.utill.StringUtils;
import com.youngball.shiro.dao.UserDao;
import com.youngball.shiro.entity.ChildResource;
import com.youngball.shiro.entity.Resource;
import com.youngball.shiro.entity.Role;
import com.youngball.shiro.entity.User;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * <p>User: Zhang Kaitao
 * <p>Date: 14-1-28
 * <p>Version: 1.0
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private PasswordHelper passwordHelper;
    @Autowired
    private RoleService roleService;

    @Autowired
    private  ResourceService resourceService;

/*
*
     * 创建用户
     * @param user
*/


    public User createUser(User user) {
        //加密密码
      /* user.setPassword(user.getPassword());*/
           /* user.setUsername(DomainClubUtils.getDomain()+user.getUsername());*/
        passwordHelper.encryptPassword(user);
        return userDao.createUser(user);
    }

    @Override
    public User updateUser(User user) {
        return userDao.updateUser(user);
    }

    @Override
    public void deleteUser(Long userId) {
        userDao.deleteUser(userId);
    }

    public User getEncodeUser(User user)
    {
        passwordHelper.encryptOldPassword(user);
        return user;
    }

    public void changePassword(Long userId, String newPassword,String oldPassword) {
        User user =userDao.findOne(userId);
        User user1=new User();
        try {
            BeanUtils.copyProperties(user1,user);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        user1.setPassword(oldPassword);
        passwordHelper.encryptOldPassword(user1);
        if (!user.getPassword().equals(user1.getPassword())){
            throw  new MyDefineException("修改前的密码不正确，请重新输入");
        }
        user.setPassword(newPassword);
        passwordHelper.encryptPassword(user);
        userDao.updateUser(user);
    }



    public void resetPassword(Long userId, String newPassword) {
        User user =userDao.findOne(userId);
        User user1=new User();
        try {
            BeanUtils.copyProperties(user1,user);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        user.setPassword(newPassword);
        passwordHelper.encryptPassword(user);
        userDao.updateUser(user);
    }

    @Override
    public User findOne(Long userId) {
        return userDao.findOne(userId);
    }

    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }

/*
*
     * 根据用户名查找用户
     * @param username
     * @return

*/

    public User findByUsername(String username) {
        return userDao.findByUsername(username);
    }

    @Override
    public User findByMyUsername(String username) {
        return this.userDao.findByMyUsername(username);
    }

/**
     * 根据用户名查找其角色
     * @param username
     * @return
     */

    public Set<String> findRoles(String username) {
        User user =findByUsername(username);
        if(user == null) {
            return Collections.EMPTY_SET;
        }
        return roleService.findRoles(user.getRoleIds().toArray(new Long[0]));
    }

    public User findByOrganization(Long id)
    {
        return userDao.findByOrganization(id);
    }
/**
     * 根据用户名查找其权限
     * @param username
     * @return
     */

    public Set<String> findPermissions(String username) {
        User user =findByUsername(username);
        if(user == null) {
            return Collections.EMPTY_SET;
        }
        return roleService.findPermissions(user.getRoleIds().toArray(new Long[0]));
    }

    @Override
    public Set<String> findMyPermissions(String username) {
        User user =findByUsername(username);
        if(user == null) {
            return Collections.EMPTY_SET;
        }
        return roleService.findMyPermissions(user.getRoleIds().toArray(new Long[0]));
    }




    @Override
    public List<User> findAllUser() {
        return this.userDao.findAllUser();
    }


    @Override
    public List<ChildResource>  findMenuPersion(User user){
        List<ChildResource> childResourceList=new ArrayList<ChildResource>();
        for (long roleId:user.getRoleIds()){
            Role role= roleService.findOne(roleId);
            if (role!=null){
                for (long rsId:role.getResourceIds()){
                    Resource resource1 =  resourceService.findOne(rsId);
                    ChildResource childResource=new ChildResource();
                    if (ObjectNullUtils.isNotBlank(resource1)) {
                        if ("menu".equals(resource1.getType().name())) {
                            if (resource1.getParentId() == 1) {
                                List<Resource> resources = resourceService.findByParent(resource1.getId());
                                childResource.setChilds(resources);
                                childResource.setResource(resource1);
                                childResourceList.add(childResource);
                            } else {
                                if (resource1.getParentId() != 0) {
                                    int i = 0;
                                    Resource resource2 = resourceService.findOne(resource1.getParentId());
                                    for (ChildResource childResource1 : childResourceList) {
                                        if (childResource1.getResource().equals(resource2)) {
                                            i++;
                                            childResource1.getChilds().add(resource1);
                                            break;
                                        }
                                    }
                                    if (i == 0) {
                                        List lists = new ArrayList();
                                        lists.add(resource1);
                                        childResource.setChilds(lists);
                                        childResource.setResource(resource2);
                                        childResourceList.add(childResource);
                                    }
                                }
                            }
                        }
                    }
                  if (resource1!=null&&"button".equals(resource1.getType().name())) {
                        Resource resources = resourceService.findOne(resource1.getParentId());
                        if (ObjectNullUtils.isNotBlank(resources)) {
                            if ("menu".equals(resources.getType().name())) {
                                Resource resources2 = resourceService.findOne(resources.getParentId());
                                if (ObjectNullUtils.isNotBlank(resources2)){
                                if (StringUtils.exist(role.getResourceIds(), resources.getId()) == -1) {
                                  List<Resource> childs=new ArrayList<Resource>();
                                    for (ChildResource resource:childResourceList){
                                        childs.add(resource.getResource());
                                    }
                                        int i = StringUtils.exist(childs, resources2);
                                        if (i == -1) {
                                            ChildResource childResource1 = new ChildResource();
                                            List lists = new ArrayList();
                                            lists.add(resources);
                                            childResource1.setChilds(lists);
                                            childResource1.setResource(resources2);
                                            childResourceList.add(childResource1);
                                        } else {
                                            if (StringUtils.exist(childResourceList.get(i).getChilds(),resources)==-1)
                                            childResourceList.get(i).getChilds().add(resources);
                                        }
                                }
                                }

                            }
                        }
                    }

                }
            }

        }
        Collections.sort(childResourceList);
        return childResourceList;
    }

    @Override
    public List<ConstantClass> getBackPersion(String username){
        Set<String> permissions= findMyPermissions(username);
        List<ConstantClass> lists=new ArrayList<ConstantClass>();
        for (String per1:permissions) {
            if (ObjectNullUtils.isNotBlank(per1)) {
                String per = per1.trim();
                String [] pp=per.split("@#&&#");
                ConstantClass constantClass = new ConstantClass();
                constantClass.setKey(pp[1]);
                constantClass.setValue(pp[0]);
                lists.add(constantClass);
            }
        }
        return lists;

    }

}
